<?php
require './JGPush/autoload.php';

use JPush\Client as JPush;
/**
 * @param string $phone 电话号码
 * @param bool $status 阶段（true 运营阶段 false 测试阶段）
 * @return bool|int 状态 true 发送成功 false 发送失败 （测试阶段返回验证码）
 */
function sendCode($phone, $status){
    // 验证手机号码
    $pattern = "/^(1[3|5|8|4|7][0-9]|15[0|3|6|7|8|9]|18[8|9])\d{8}$/is";
    preg_match($pattern, $phone, $arr);
    if(empty($arr)){
        return false;
    }

    $code_num = rand(100001,999999);    //验证码

    $sms = M('sms_code');
    $map['phone'] = $phone;
    $sms_arr = $sms->where($map)->find();
    if(empty($sms_arr)){
        $sms_data = array(
            'phone' => $phone,
            'code' => $code_num,
            'time' => time()
        );
        $sms_res = $sms->add($sms_data);
    }else{
        $sms_data = array(
            'code' => $code_num,
            'time' => time()
        );
        $sms_res = $sms->where($map)->save($sms_data);
    }

    if($sms_res !== false){
        if($status){ //发送验证码
            $user = 'cqflfw';    //短信账户
            $pass = 'youqu26';   //短信密码

            $url='http://www.qybor.com:8500/shortMessage';
            $timeout = 20;
            $msg="您好,您的验证码:". $code_num ."三分钟内有效,客服不会向您索要验证码。【服来服往】";
            $post_data = "username=". $user ."&passwd=". $pass ."&phone=". $phone ."&msg=".urlencode($msg)."&needstatus=true&port=&sendtime=";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $res = curl_exec($ch);
            curl_close($ch);
            $res_obj = json_decode($res);
            if($res_obj->respcode == 0){
                return true;
            }else{
                return false;
            }
        }else{ //不发送验证码
            return $code_num;
        }
    }else{
        return false;
    }
}

/**
 * 校验验证码
 * @param string $phone 电话号码
 * @param string $code 验证码
 * @return int 状态（0 验证码错误 1 验证码正确 2 验证码失效）
 */
function checkPhoneCode($phone, $code){
    $smsCode = M('smsCode');
    $map['phone'] = $phone;
    $sms_info = $smsCode->where($map)->find();
    if(empty($sms_info)){
        return 0;//验证码错误
    }else{
        if($sms_info['code'] == $code){
            if((time() - $sms_info['time']) > (30*60)){
                return 2;//验证码失效
            }else{
                return 1;//验证码正确
            }
        }else{
            return 0;//验证码错误
        }
    }
}

/**
 * 获取配置项
 * @param string $str 配置项名（多个用','隔开）
 * @return mixed 配置项值
 */
function getAppConfig($str){
    $con_arr = explode(',',$str);
    $Config = M('config');
    foreach ($con_arr as $k => $v){
        $map['config_name'] = $v;
        $return[$v] = $Config->where($map)->getField('config_value');
    }
    return $return;
}

/**
 * 生成二维码
 * @param $Data string 生成二维码的数据
 * @param $FileName
 * @param bool $PicPath
 * @param bool $LogoPath
 * @param string $Size
 * @param string $Level
 * @param int $Padding
 * @return string
 */
function createQRCode($Data, $FileName, $PicPath=false, $LogoPath=false, $Size='8', $Level='Q', $Padding=2){
    vendor("phpqrcode.phpqrcode");//引入工具包

    $Path = $PicPath?$PicPath:'Uploads/QRCode/';

    if(!is_dir($Path)){//目录不存在时创建保存目录
        mkdir($Path);
    }

    $SaveName = uniqid().'.png';//构建文件名
    $SavePath = $Path.$SaveName;//构建保存的完整路径及文件名

    if(empty($LogoPath) || $LogoPath == false){//不包含LOGO
        if($FileName == false){//浏览器输出
            QRcode::png($Data,false,$Level,$Size,$Padding);
        }else{//保存到文件夹
            QRcode::png($Data,$SavePath,$Level,$Size,$Padding);
        }
    }else{//包含LOGO
        QRcode::png($Data,$SavePath,$Level,$Size,$Padding);

        $QR = imagecreatefromstring(file_get_contents($SavePath));
        $Logo = imagecreatefromstring(file_get_contents($LogoPath));

        $QRWidth = imagesx($QR);
        $QRHeight = imagesy($QR);

        $LogoWidth = imagesx($Logo);
        $LogoHeight = imagesy($Logo);

        $LogoQRWidth = $QRWidth / 5;
        $Times = $LogoWidth / $LogoQRWidth;
        $LogoQRHeight = $LogoHeight / $Times;

        $FromWidth = ($QRWidth - $LogoQRWidth) / 2;

        imagecopyresampled($QR,$Logo,$FromWidth,$FromWidth,0,0,$LogoQRWidth,$LogoQRHeight,$LogoWidth,$LogoHeight);

        if($FileName == false){//浏览器输出
            Header("Content-type:image/png");
            imagepng($QR);
        }else{//保存到文件夹
            imagepng($QR,$SavePath);
        }
    }
    return '/'.$SavePath;
}

/**
 * 双端自定义消息
 * @param $arr
 * @return bool
 */
function JPushMessage($arr){
    $app_key = C('PUSH_APP_KEY');
    $secrets = C('PUSH_SECRETS');

    $alias = $arr['alias'];
    $title = $arr['title'];
    $content = $arr['content'];
    $data = $arr['data'];
    $client = new JPush($app_key, $secrets);

    try{
        $res = $client->push()
            ->setPlatform(array('ios','android'))
            ->addAlias($alias)
            ->message($content, array(
                'title' => $title,
                'content_type' => 'text',
                'extras' => $data
            ))
            ->setOptions(100000,0,null,true)
            ->send();
    }catch (\Exception $e) {
        $res = array();
    }

    if($res['http_code'] == 200){
        return true;
    }else{
        return false;
    }
}
/**
 * 极光自定义通知(双端)
 * @param $arr
 * @return bool
 */
function push_all_notice($arr)
{
    $app_key = C('PUSH_APP_KEY');
    $secrets = C('PUSH_SECRETS');

    $alias = $arr['alias']; // 推送标识
    $title = $arr['title']; // 标题
    $content = $arr['content']; // 内容
    $data = $arr['data']; // 数据
    $client = new JPush($app_key, $secrets);
    try
    {
        $client_res = $client->push()
            ->setPlatform(array('ios','android'))
            ->addTag($alias)
            ->setNotificationAlert($title)
            ->iosNotification($content, array(
                'sound' => 'default',
                'extras' => $data
            ))
            ->androidNotification($content, array(
                'title' => $title,
                'extras' => $data
            ))
            ->options(array(
                'apns_production' => false // true 生产环境 false 开发环境
            ))
            ->send();
    }
    catch (\Exception $e)
    {
        $client_res = array();
    }
    if ($client_res['http_code'] == 200)
    {
        return true;
    }
    else
    {
        return false;
    }
}


/**
 * 用于生成excel文件的函数
 * @param $data 生成excel的数据(二维数组形式)
 * @param null $savefile 生成excel的文件名(保不指定,则为当前时间戳)
 * @param null $title 生成excel的表头(一维数组形式)
 * @param string $sheetname 生成excel的sheet名称(缺省为sheet1)
 */
function exportExcel($data,$savefile=null,$title=null,$sheetname='sheet1'){
    //若没有指定文件名则为当前时间戳
    if(is_null($savefile)){
        $savefile=time();
    }
    //若指字了excel表头，则把表单追加到正文内容前面去
    if(is_array($title)){
        array_unshift($data,$title);
    }
    Vendor('PHPExcel.Classes.PHPExcel');
    Vendor('PHPExcel.Classes.PHPExcel.IOFactory');
    Vendor('PHPExcel.Classes.PHPExcel.Reader.Excel5');
    $objPHPExcel = new PHPExcel();
    $objActSheet = $objPHPExcel->getActiveSheet();
    //Excel内容
    foreach($data as $k => $v){
        $obj=$objPHPExcel->setActiveSheetIndex(0);
        $row=$k+1;//行
        $nn=0;
        foreach($v as $vv){
            $col=chr(65+$nn);//列
            $obj->setCellValue($col.$row,$vv);//列,行,值
            $nn++;
        }
    }
    // $objActSheet->getColumnDimension('A')->setAutoSize(true);
    // $objActSheet->getColumnDimension('J')->setAutoSize(true);
    // $objActSheet->getColumnDimension('U')->setAutoSize(true);
    // $objActSheet->getColumnDimension('V')->setAutoSize(true);
    // $objActSheet->getColumnDimension('W')->setAutoSize(true);
    // $objPHPExcel->getActiveSheet()->getStyle('Q1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
    // $objPHPExcel->getActiveSheet()->getStyle('Q1')->getFill()->getStartColor()->setARGB('FFFF0014');
    // $objPHPExcel->getActiveSheet()->setTitle($sheetname);
    // $objPHPExcel->setActiveSheetIndex(0);
    ob_end_clean();//清除缓冲区,避免乱码
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$savefile.'.xls"');
    header('Cache-Control: max-age=0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}
/**
 * PHP生成唯一邀请码
 * @return string
 */
function make_coupon_card() {
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0,25)]
    .strtoupper(dechex(date('m')))
    .date('d').substr(time(),-5)
    .substr(microtime(),2,5)
    .sprintf('%02d',rand(0,99));
    for(
        $a = md5( $rand, true ),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
        $d = '',
        $f = 0;
    $f < 8;
    $g = ord( $a[ $f ] ),
    $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
    $f++
    );
    return $d;
}

/**
 * [xh_validate]
 * 函数用途描述: 数据验证
 * @date:  2017-10-12
 * @author: xiaohui
 * @param: [variable]
 * @param: array      $arr array('验证字段','验证规则','提示语',['验证模式'])
 * @param: 验证规则 require [不能为空]
 * @param: 验证规则 email   [验证是否是email格式]
 * @param: 验证规则 url     [验证是否是网址]
 * @param: 验证规则 phone   [验证是否是手机号]
 * @param: 验证规则 number  [验证是否是数字]
 * @param: 验证模式 regex   [正则验证，定义的验证规则是一个正则表达式（默认）] 
 * @param: 验证模式 in      [验证是否在某个范围内，定义的验证规则可以是一个数组或者逗号分割的字符串] array(1,2,3)  "1,2,3"
 * @param: 验证模式 length  [验证长度，定义的验证规则可以是一个数字（表示固定长度）或者数字范围（例如3,12 表示长度从3到12的范围）]
 * @example: array(array('user_id', 'require', '用户id不能为空'));
 * @return [type]          [description]
 */
function xh_validate($arr = array(), $data = array()) {
    if (is_array($arr) && !empty($arr) && is_array($data) && !empty($data)) {
        foreach ($arr as $k => $v) {

            // 判断键值是否有
            if ($data[$v[0]] === null) {
                $reData = array(
                    'status' => 0,
                    'msg' => $v[2],
                    'data' => ''
                );
                return $reData;
                break;
            }

            if (empty($v[3])) $v[3] = 'regex';
            // 正则验证 
            if ($v[3] == 'regex') {
                // 默认正则
                $pattern = $v[1];
                // if ($v[1] == 'require') $pattern = "/^\s+/";
                if ($v[1] == 'email') $pattern = "/\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/";
                if ($v[1] == 'url') $pattern = "/^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/";
                if ($v[1] == 'number') $pattern = "/^[0-9]+(.[0-9])*$/";
                if ($v[1] == 'phone') $pattern = "/^(1[1-9][0-9]|15[0|3|6|7|8|9]|18[8|9])\d{8}$/is";

                if ($v[1] == 'require') {
                    if ($data[$v[0]] === '') {
                        $reData = array(
                            'status' => 0,
                            'msg' => $v[2],
                            'data' => ''
                        );
                        break;
                    } else {
                        $reData = true;
                    }
                } else {
                    preg_match($pattern,$data[$v[0]],$validate);
                    if (empty($validate)) {
                        $reData = array(
                            'status' => 0,
                            'msg' => $v[2],
                            'data' => ''
                        );
                        break;
                    } else {
                        $reData = true;
                    }
                }
            }
            // 包含验证
            if ($v[3] == 'in') {
                if (!is_array($v[1])) {
                    $data_arr = explode(',', $v[1]);
                } else {
                    $data_arr = $data[$v[0]];
                }
                if (in_array($data[$v[0]], $data_arr)) {
                    $reData = true;
                } else {
                    $reData = array(
                        'status' => 0,
                        'msg' => $v[2],
                        'data' => ''
                    );
                    break;
                }
            }
            // 长度验证
            if ($v[3] == 'length') {
                $data_len = mb_strlen($data[$v[0]],'UTF-8');
                if (strpos($v[1], ',') !== false) {
                    $len_arr = explode(',', $v[1]);
                    if ($data_len >= $len_arr[0] && $data_len <= $len_arr[1]) {
                        $reData = true;
                    } else {
                        $reData = array(
                            'status' => 0,
                            'msg' => $v[2],
                            'data' => ''
                        );
                        break;
                    }
                } else {
                    if ($data_len == $v[1]) {
                        $reData = true;
                    } else {
                        $reData = array(
                            'status' => 0,
                            'msg' => $v[2],
                            'data' => ''
                        );
                        break;
                    }
                }
            }
        }
    } else {
        $reData = array(
            'status' => 0,
            'msg' => '验证错误',
            'data' => ''
        );
    }

    return $reData;
}